import React, { useState, useEffect, useRef, useReducer } from 'react';
import { formatDate, formatSize } from '@/utils/format';
import { OperationPanel } from '@/components/FilePanel/operationPanel/operationPanel'
import { DisplayPanelProps } from './displayPanel.interface'
import { NodeItem, NodeItems, Operations } from '@/components/FilePanel/schemas/panelInterface'
import { panelPosition } from '../operationPanel/operationPanel.interface';


import './displayPanel.css';
import { IconFileCode, IconFolderClose } from '@/icons/file';
import {
  StyledDirectoryContainer,
  StyledFileIcon,
  StyledFileList,
  StyledFileItem,
  StyledFileName,
  StyledFileSize,
  StyledFileDate,
  StyledSelectionBox
} from './displayPanel.styles'

interface NodeItem_with_Control extends NodeItem {
  selected: boolean;
}

type NodeItems_with_Controls = NodeItem_with_Control[];

interface State {
  nodeItems: NodeItems_with_Controls;
  selectedItems: NodeItem[];
  panelPosition: panelPosition;
  panelVisible: boolean;
}

type Action =
  | { type: 'SET_NODE_ITEMS'; payload: NodeItems_with_Controls }
  | { type: 'CLEAR_SELECTED' }
  | { type: 'ADD_SELECTED'; payload: NodeItem }
  | { type: 'SET_PANEL_POSITION'; payload: panelPosition }
  | { type: 'SET_PANEL_VISIBLE'; payload: boolean };

const initialState: State = {
  nodeItems: [],
  selectedItems: [],
  panelPosition: { x: 0, y: 0 },
  panelVisible: false
};

const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'SET_NODE_ITEMS':
      return { ...state, nodeItems: action.payload };
    case 'CLEAR_SELECTED':
      return { ...state, selectedItems: [] };
    case 'ADD_SELECTED':
      return { 
        ...state, 
        selectedItems: [...state.selectedItems, action.payload],
        nodeItems: state.nodeItems.map(node => ({
          ...node,
          selected: node.path === action.payload.path
        }))
      };
    case 'SET_PANEL_POSITION':
      return { ...state, panelPosition: action.payload };
    case 'SET_PANEL_VISIBLE':
      return { ...state, panelVisible: action.payload };
    default:
      return state;
  }
};

const DisplayPanel: React.FC<DisplayPanelProps> = ({nodeItem_list, currentPath}) => {
  const [state, dispatch] = useReducer(reducer, {
    ...initialState,
    nodeItems: nodeItem_list.map(item => ({ ...item, selected: false }))
  });

  const panelRef = useRef<HTMLDivElement>(null);

  const handleClickMenuItem = (e: React.MouseEvent, item: NodeItem_with_Control) => {
    e.preventDefault();
    dispatch({ type: 'CLEAR_SELECTED' });
    dispatch({ type: 'ADD_SELECTED', payload: item });
  };

  const handleContextMenu = (e: React.MouseEvent, item: NodeItem_with_Control) => {
    e.preventDefault();
    dispatch({ type: 'CLEAR_SELECTED' });
    dispatch({ type: 'ADD_SELECTED', payload: item });
    dispatch({ type: 'SET_PANEL_POSITION', payload: { x: e.clientX, y: e.clientY } });
    dispatch({ type: 'SET_PANEL_VISIBLE', payload: true });
  };

  // 处理面板外点击关闭
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (state.panelVisible && panelRef.current && !panelRef.current.contains(e.target as Node)) {
        dispatch({ type: 'SET_PANEL_VISIBLE', payload: false });
      }
    };

    window.addEventListener('click', handleClickOutside);
    return () => window.removeEventListener('click', handleClickOutside);
  }, [state.panelVisible]);

  return (
    <StyledDirectoryContainer>
      <StyledFileList>
        {state.nodeItems.map((file) => (
          <StyledFileItem
            selected={file.selected}
            key={file.path}
            data-path={file.path}
            onClick={(e) => handleClickMenuItem(e, file)}
            onContextMenu={(e) => handleContextMenu(e, file)}
          >
            
            <StyledFileIcon>
                {
                    file.isDirectory?
                    <IconFolderClose height={20} width={20} color="#d1a062"/>:
                    <IconFileCode height={20} width={20} color="#d1a062"/>
                }
            </StyledFileIcon>
            
            <StyledFileName>{file.Name}</StyledFileName>
            <StyledFileSize>{file.isDirectory ? '--' : formatSize(file.size)}</StyledFileSize>
            <StyledFileDate>{formatDate(file.modifiedTime)}</StyledFileDate>
          </StyledFileItem>
        ))}
      </StyledFileList>
    
      {state.panelVisible && state.selectedItems.length > 0 && (
        <div ref={panelRef}>
          <OperationPanel
            position={state.panelPosition}
            itemInfo={state.selectedItems[0]}
          />
        </div>
      )}
    </StyledDirectoryContainer>
  )
};

export default DisplayPanel;

